/**
 * @copyright (C) COPYRIGHT 2022 Fortiortech Shenzhen
 * @file      MotorControlFunction.c
 * @author    Fortiortech  Appliction Team
 * @since     Create:2021-11-07
 * @date      Last modify:2022-07-14
 * @note      Last modify author is Marcel He
 * @brief
 */


#include <MyProject.h>

CurrentOffset      xdata mcCurOffset;  ///< 电流采样偏置电压采集缓存

/**
 * @brief      对FOC的相关寄存器进行配置,先清理寄存器，后配置，最后使能
 * @exception  初始化FOC，需要先关闭DRVIVER，对FOC寄存器配置完成后，使能FOC再打开DRVIVER,否则可能导致第一拍电流采样错误
 * @date       2022-07-14
 */
void FOC_Init(void)
{

}


/**
 * @brief     预充电分三步，第一步是对U相进行预充电，第二步是对V两相进行预充电;第三步是对W三相进行预充电。
 * @brief     低压应用一般不需要预充电，在customer.h禁止预充电功能寄即可
 * @exception 在低功率高压应用中，过流值较小，充电电流过大可能导致触发硬件过流, 需要注意检查
 * @date      2022-07-14
 */
void Motor_Charge(void)
{

}


/**
 * @brief     开启次功能启动时候会将电机强拉到 设定角度，之后再启动
 * @date      2022-07-14
 */
void Motor_Align(void)
{

}

/**
 * @brief     顺逆风处理函数
 * @date      2022-09-14
 */
void Motor_TailWind(void)
{
   
}




/**
 * @brief     FOC计算方法顺逆风检测 的顺风启动配置函数
 * @date      2022-07-14
 */
void Motor_FocTailWind_Open(void)
{
    /* 启动方式选择 */
    FOC_EFREQACC        = 500;
    FOC_EFREQMIN        = MOTOR_OMEGA_RAMP_MIN;
    FOC_EFREQHOLD       = MOTOR_OMEGA_RAMP_END;
    //    SetBit(FOC_CR1, EFAE);
    //    ClrBit(FOC_CR1, RFAE);
    //    SetBit(FOC_CR1, ANGM);
    mcFocCtrl.State_Count   = 0;        // 取消ATO爬坡
    FOC_EKP                 = OBSW_KP_GAIN_RUN4;                       // 估算器里的PI的KP
    FOC_EKI                 = OBSW_KI_GAIN_RUN4;                       // 估算器里的PI的KI
}


/**
 * @brief     静止启动配置函数
 * @date      2022-07-14
 */
void Motor_Static_Open(void)
{
    FOC_Init();
	

}


/*  -------------------------------------------------------------------------------------------------
    Function Name  : MC_Stop
    Description    : inital motor control parameter
    Date           : 2021-04-10
    Parameter      : None
    ------------------------------------------------------------------------------------------------- */
void MC_Stop(void)
{

}


/**
 * @brief     三下桥刹车
 * @date      2022-07-14
 */
void MC_Break(void)
{
    MOE         = 1;
    ClrBit(DRV_CR, FOCEN);  // 关闭FOC
    /*  软件设置PWM占空比输出以上桥为参考，配置为互补输出时下桥反向 */
    ClrBit(DRV_CR, OCS);    // OCS = 0, DRV_COMR;  OCS = 1, FOC/SVPWM/SPWM
    SetBit(DRV_CR, DRVEN);  // 计数器使能      0-->Disable 1-->Enable
    DRV_CMR = 0x0015;       //  关闭上桥输出，开启下桥输出
    DRV_DR  = (DRV_ARR) + 4 ; // ARR+4为全开
}


/**
 * @brief     控制变量上电初始化,包括保护参数的初始化、电机状态初始化
 * @brief     上电只运行一次
 * @date      2022-07-14
 */
void MotorcontrolInit(void)
{
    /*****电机状态机时序变量***********/
    McStaSet.SetMode                    = 0;
    /**********电机目标方向*************/
    #if (FR_MODE == CW)
    {
        mcFocCtrl.FR                    = CW;
    }
    #else
    {
        mcFocCtrl.FR                    = CCW;
    }
    #endif //end IRMODE
    /* -----电流偏置校准变量初始化----- */
    mcCurOffset.IuOffsetSum            = 16383;
    mcCurOffset.IvOffsetSum            = 16383;
    mcCurOffset.Iw_busOffsetSum        = 16383;
    mcPwmInput.TimerARR                = 65535;
    
    memset(&Restart, 0, sizeof(FaultRecoverTypedef));//重启变量清零
}


/**
 * @brief     初始化电机参数，每次电机重启均会被调用
 * @warning   需要注意填写的变量是否可以在此时刻被初始化
 * @date      2022-07-14
 */
void VariablesPreInit(void)
{
    //缺相变量清零
    Fault.PhaseLoss.Lphasecnt           = 0;
    Fault.PhaseLoss.AOpencnt            = 0;
    Fault.PhaseLoss.BOpencnt            = 0;
    Fault.PhaseLoss.COpencnt            = 0;
    Fault.PhaseLoss.ABCOpenCnt          = 0;
    Fault.PhaseLoss.mcLossPHRecCount    = 0;
    Fault.PhaseLoss.DectDealyCnt        = 0;
    // 电压保护
    Fault.Voltage.OverVoltDetecCnt      = 0;
    Fault.Voltage.UnderVoltDetecCnt     = 0;
    Fault.Voltage.VoltRecoverCnt        = 0;
    Fault.Voltage.BusVoltDetecCnt       = 0;
    //    Fault.Voltage.DectDealyCnt          = 0;
    Fault.Voltage.OverVoltageVal        = OVER_VOLTAGE_PROTECT;
    Fault.Voltage.UnderVoltageVal       = UNDER_VOLTAGE_PROTECT;
    // 堵转保护
    Fault.Stall.OverSpeedVal            = STALL_MAX_SPEED;
    Fault.Stall.UnderSpeedVal           = STALL_MIN_SPEED;
    Fault.Stall.DectDealyCnt            = 0;
    Fault.Stall.Mode0DectCnt            = 0;
    Fault.Stall.SpeedErr                = 0;
    Fault.Stall.DeviSpeedCnt            = 0;
    Fault.Stall.EsDectCnt               = 0;
    Fault.Stall.SpeedDectCnt            = 0;
    Fault.Stall.SpeedMinCnt             = 0;
    Fault.Stall.DectDealyCnt            = 0;
    Fault.Stall.Type                    = 0;
    McStaSet.SetMode                    = 0;
    mcFocCtrl.CtrlMode                  = 0;
    mcFocCtrl.ChargeStep                = 0;
    mcFocCtrl.Flg_ATORampEnd            = 0;
    mcFocCtrl.Start_Mode   = STATIC_START;//初始化为静止启动    
    
}




/**
 * @brief     上电时，先对硬件电路的电流进行采集，写入对应的校准寄存器中。
              调试时，需观察mcCurOffset结构体中对应变量是否在范围内。采集结束后，OffsetFlag置1。
 * @date      2022-07-14
 */
void GetCurrentOffset(void)
{
    SetBit(ADC_CR, ADCBSY);             // 使能ADC
    
    while (ReadBit(ADC_CR, ADCBSY));
    
    #if (Shunt_Resistor_Mode == Single_Resistor)                   //单电阻模式
    {
        mcCurOffset.Iw_busOffsetSum += ((ADC4_DR & 0x7ff8));
        mcCurOffset.Iw_busOffset     = mcCurOffset.Iw_busOffsetSum >> 4;
        mcCurOffset.Iw_busOffsetSum -= mcCurOffset.Iw_busOffset;
    }
    #elif (Shunt_Resistor_Mode == Double_Resistor)                 //双电阻模式
    {
        mcCurOffset.IuOffsetSum     += ((ADC0_DR & 0x7ff8));
        mcCurOffset.IuOffset         = mcCurOffset.IuOffsetSum >> 4;
        mcCurOffset.IuOffsetSum     -= mcCurOffset.IuOffset;
        mcCurOffset.IvOffsetSum     += ((ADC1_DR & 0x7ff8));
        mcCurOffset.IvOffset         = mcCurOffset.IvOffsetSum >> 4;
        mcCurOffset.IvOffsetSum     -= mcCurOffset.IvOffset;
    }
    #elif (Shunt_Resistor_Mode == Three_Resistor)                 //三电阻模式
    {
        mcCurOffset.IuOffsetSum     += ((ADC0_DR & 0x7ff8));
        mcCurOffset.IuOffset         = mcCurOffset.IuOffsetSum >> 4;
        mcCurOffset.IuOffsetSum     -= mcCurOffset.IuOffset;
        mcCurOffset.IvOffsetSum     += ((ADC1_DR & 0x7ff8));
        mcCurOffset.IvOffset         = mcCurOffset.IvOffsetSum >> 4;
        mcCurOffset.IvOffsetSum     -= mcCurOffset.IvOffset;
        mcCurOffset.Iw_busOffsetSum += ((ADC4_DR & 0x7ff8));
        mcCurOffset.Iw_busOffset     = mcCurOffset.Iw_busOffsetSum >> 4;
        mcCurOffset.Iw_busOffsetSum -= mcCurOffset.Iw_busOffset;
    }
    #endif
    mcCurOffset.OffsetCount++;
    
    if (mcCurOffset.OffsetCount > Calib_Time)
    {
        mcCurOffset.OffsetFlag = 1;
		#if (OffsetProtectEn)
        {
            Fault_GetCurrentOffset();     //偏置电压保护
        }
        #endif
    }
}



/**
 * @brief     关闭输出，关闭FOC，电机切换到mcReady状态被调用一次
 * @date      2022-07-14
 */
void Motor_Ready(void)
{
    if (McStaSet.SetFlag.CalibFlag == 0)
    {
        McStaSet.SetFlag.CalibFlag = 1;
        MOE               = 0;
        ClrBit(DRV_CR, FOCEN);
        ClrBit(DRV_CR, DRVEN);
    }
}


/**
 * @brief     电机初始化，对电机相关变量、PI进行初始化设置,关闭FOC所需要使用到的ADC
 * @note      关闭FOC所需要使用到的ADC，FOC模块会自动调用相应ADC 无需外部使能
 * @date      2022-07-14
 */

void Motor_Init(void)
{
    VariablesPreInit();                           // 电机相关变量初始化
}

